package com.kingsoft.labs.tangram.util.io;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.*;

import com.kingsoft.labs.tangram.domain.Result;

public class JSONHelper {
	public static JSONObject serializeMap(Map<String, String> param) throws JSONException {
		JSONObject json = new JSONObject();
		for (Map.Entry<String, String> entry : param.entrySet()) {
			json.put(entry.getKey(), entry.getValue());
		}
		return json;
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String, String> deserializeMap(JSONObject json) {
		HashMap<String, String> map = new HashMap<String, String>();
		Iterator<String> iter = json.keys();
		while (iter.hasNext()) {
			String key = iter.next();
			try {
				map.put(key, json.getString(key));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	public static JSONObject serializeResult(Result result) {
		JSONObject json = new JSONObject();
		try {
			json.put("returnCode", result.returnCode);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json;
	}
	
	public static Result deserializeResult(JSONObject json) {
		Result result = new Result();
		try {
			result.returnCode = json.getInt("returnCode");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}
}
